package com.starsoft.trade.trader;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import com.starsoft.frame.util.StringUtil;
import com.starsoft.trade.bean.TradeAcount;

public class TraderFatory {

	@Autowired
	CacheManager cacheManager;
	
	@Autowired
	TraderContextService contextService;
	
	Map<String, String> traderMap;
	
	Map<String, Map<String, String>> traderApiMap;
	
	String cacheName = "traderCache";
	
	public Trader getTrader(TradeAcount acount){
		String traderKey = acount.getAcountId()+acount.getExSystem()+acount.getExSystemConfig();
		Trader trader = getFromCache(traderKey);
		if (trader == null) {
			String exSystemCode = acount.getExSystem();
			if (StringUtil.isEmpty(exSystemCode)) {
				throw new RuntimeException("未配置交易接口");
			}
			if (!traderMap.containsKey(exSystemCode)) {
				throw new RuntimeException("交易接口配置错误");
			}
			try {
				String traderClass = traderMap.get(exSystemCode);
				trader = (Trader) Class.forName(traderClass).newInstance();
				trader.init(acount, traderApiMap.get(exSystemCode), contextService);
				trader.login();
				putInCache(traderKey, trader);
			} catch (Exception e) {
				throw new RuntimeException("创建trader失败,", e);
			}
		}
		return trader;
	}

	private Trader getFromCache(String traderKey){
		Cache cache = cacheManager.getCache(cacheName);
		Trader trader = cache.get(traderKey,Trader.class);
		return trader;
	}
	
	private void putInCache(String traderKey, Trader trader){
		Cache cache = cacheManager.getCache(cacheName);
		cache.put(traderKey, trader);
	}
	
	public Map<String, String> getTraderMap() {
		return traderMap;
	}

	public void setTraderMap(Map<String, String> traderMap) {
		this.traderMap = traderMap;
	}

	public Map<String, Map<String, String>> getTraderApiMap() {
		return traderApiMap;
	}

	public void setTraderApiMap(Map<String, Map<String, String>> traderApiMap) {
		this.traderApiMap = traderApiMap;
	}
	
}
